﻿using Awsc.DataAcquisitionSys.Core.DataAcquisition;
using Awsc.DataAcquisitionSys.Core.Model.Config;

namespace Awsc.DataAcquisitionSys.Core.Services.DataAcquisition.DataCollectors.Sensors
{
    public class ConventionalSensor:Sensor
    {
        protected override void CalculateValue()
        {
            var value = this.OutputValue;
            if(value==null|| !(value is double))
            {
                base.CalculateValue();
                return;
            }
            var sensorvalue = (double)value;
            double mesureValue = (double)sensorvalue;
            var config = this.SensorConfig as RegisterConfig;
            if(config==null)
            {
                base.CalculateValue();
            }
            //过滤传感器在0值时的误差
            if (sensorvalue < 4.15)
            {
                sensorvalue = 4.0;
            }
            if (sensorvalue >= config.OutputMax)
            {
                mesureValue = config.OutputMax;
            }
            else if (sensorvalue <= config.OutputMin)
            {
                sensorvalue = config.OutputMin;
            }

            //采集电流占比=采集传感器电流值/传感器范围
            double output = (sensorvalue - config.OutputMin) / (config.OutputMax - config.OutputMin);
            //测量值=(测量范围最小值有可能为负数，所以RangeMin)+测量值范围*采集电流占比-校准值Zero
            double range = config.RangeMin + (config.RangeMax - config.RangeMin) * output - config.Zero;
            if (range < config.RangeMin)
            {
                range = config.RangeMin;
            }
            if (range > config.RangeMax)
            {
                range = config.RangeMax;
            }
            mesureValue = range * config.KValue;

            //处理转盘扭矩和转盘马达的关系
            if (Name == "转盘扭矩")
            {
                var coil = GlobalDeviceManager.Instance.GetSensor("转盘四驱");
                if (coil?.CurrentValue != null && (bool)(coil.CurrentValue))
                {
                    mesureValue = mesureValue * 2;
                }
            }
            this.CurrentValue = mesureValue;
        }
    }
}
